package services

import (
	"context"
	"errors"
	"go.didapinche.com/foundation/plat-echo/app/ops/models"
	"go.didapinche.com/foundation/plat-echo/app/ops/repositories"
	"go.didapinche.com/time"
)

type TempTypeService interface {
	FindAll(ctx context.Context) ([]*models.TempType, error)
	Create(ctx context.Context, tempType *models.TempType) (*models.TempType, error)
	Update(ctx context.Context, tempType *models.TempType) (*models.TempType, error)
	Delete(ctx context.Context, ID uint64) error
	FindByTemplateType(ctx context.Context, templateType models.TypeEnum) ([]*models.TempType, error)
}

type ruleTypeService struct {
	tempTypeRepo repositories.TempTypeRepository
}

func NewTempTypeService(tempTypeRepo repositories.TempTypeRepository) TempTypeService {
	return &ruleTypeService{
		tempTypeRepo: tempTypeRepo,
	}
}

func (r *ruleTypeService) FindAll(ctx context.Context) ([]*models.TempType, error) {
	return r.tempTypeRepo.FindAll(ctx)
}

func (r *ruleTypeService) Create(ctx context.Context, tempType *models.TempType) (*models.TempType, error) {
	exists, _ := r.tempTypeRepo.FindByKey(ctx, tempType.Key)
	if exists != nil {
		return nil, errors.New("key 冲突")
	}

	tempType.CreateTime = time.Now()
	err := r.tempTypeRepo.Create(ctx, tempType)
	return tempType, err
}

func (r *ruleTypeService) Update(ctx context.Context, tempType *models.TempType) (*models.TempType, error) {
	rule, err := r.tempTypeRepo.FindByID(ctx, tempType.ID)
	if err != nil {
		return nil, err
	}
	if rule.Key != tempType.Key {
		return nil, errors.New("key 不一致")
	}

	rule.Name = tempType.Name
	rule.Key = tempType.Key
	rule.Order = tempType.Order
	err = r.tempTypeRepo.Update(ctx, rule)
	return rule, err
}

func (r *ruleTypeService) Delete(ctx context.Context, ID uint64) error {
	count, _ := r.tempTypeRepo.FindByTypeID(ctx, ID)
	if count > 0 {
		return errors.New("分类下有模板")
	}
	return r.tempTypeRepo.Delete(ctx, ID)
}

func (r *ruleTypeService) FindByTemplateType(ctx context.Context, templateType models.TypeEnum) ([]*models.TempType, error) {
	return r.tempTypeRepo.FindByTemplateType(ctx, templateType)
}
